package com.ebt.m.proposal_v2.mvp.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.ebt.m.AppContext;
import com.ebt.m.R;
import com.ebt.m.data.bean.CardInfo;
import com.ebt.m.event.ProposalListTabCheckedEvent;
import com.ebt.m.proposal_v2.utils.ProposalUtils;
import com.ebt.m.proposal_v2.base.Constant;
import com.ebt.m.proposal_v2.bean.ArgProposalDetail;
import com.ebt.m.proposal_v2.bean.AudioTap;
import com.ebt.m.proposal_v2.bean.ShareBody;
import com.ebt.m.proposal_v2.dao.ProposalApi;
import com.ebt.m.proposal_v2.dao.RetroFileDownloader;
import com.ebt.m.proposal_v2.dao.file.OnDownloadListener;
import com.ebt.m.proposal_v2.dao.request.ParamProposalTap;
import com.ebt.m.proposal_v2.dao.request.ParamSaveProposalTaps;
import com.ebt.m.proposal_v2.dao.response.ResponseProposalTap;
import com.ebt.m.proposal_v2.dao.response.ResponseSaveTaps;
import com.ebt.m.proposal_v2.dao.response.ResponseSendProposal;
import com.ebt.m.proposal_v2.dao.response.ResponseTapDelete;
import com.ebt.m.proposal_v2.dao.response.ResponseTapFile;
import com.ebt.m.proposal_v2.mvp.base.BasePresenter;
import com.ebt.m.proposal_v2.mvp.contract.ProposalDetailContract;
import com.ebt.m.proposal_v2.retrofit.OnResponseListener;
import com.ebt.m.proposal_v2.retrofit.ResponseError;
import com.ebt.m.proposal_v2.retrofit.ResponsePage;
import com.ebt.m.proposal_v2.widget.dialog.ProposalTapDialog;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.commons.utils.Logger;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author archer.qi
 * Created on 2017/5/15.
 */
public class ProposalDetailPresenter extends BasePresenter<ProposalDetailContract.View> implements ProposalDetailContract.Presenter {

    /* 该计划书下从属的录音*/
    private AudioTap mAudioTapBindingProposal;

    public ProposalDetailPresenter(Context context, ProposalDetailContract.View view) {
        super(context, view);
    }

    @Override
    public void start() {

    }

    @Override
    public void getProposalTap(String proposalId) {
        ProposalApi.getInstance(mContext).getProposalTapById(proposalId, new OnResponseListener<List<ResponseProposalTap>>() {
            @Override
            public void onSuccess(List<ResponseProposalTap> body, ResponsePage page) {
                if (body != null && body.size() > 0) {
                    ResponseProposalTap mTap = body.get(0);
                    if (mTap != null) {
                        if (mAudioTapBindingProposal == null) {
                            mAudioTapBindingProposal = new AudioTap();
                        }
                        mAudioTapBindingProposal.id = mTap.fileId;
                        mAudioTapBindingProposal.url = mTap.content;
                        mAudioTapBindingProposal.duration = mTap.duration;
                        mAudioTapBindingProposal.type = 2;
                        mAudioTapBindingProposal.fromServer = true;
                        downloadProposalTap(mTap.content);
                    }
                }
            }

            @Override
            public void onFailure(ResponseError error) {

            }
        }, mView);
    }

    @Override
    public void downloadProposalTap(String url) {
        RetroFileDownloader.getDownloader().download(url, Constant.outputTap, new OnDownloadListener() {
            @Override
            public void onResponse(String url, String target) {
                File outputTapFile = new File(target);
                if (outputTapFile.exists() && outputTapFile.length() > 0) {
                    mAudioTapBindingProposal.path = target;
                    mView.setAudio(mAudioTapBindingProposal.duration);
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Logger.e("download tap failure, code: " + code + ", message: " + msg);
                mAudioTapBindingProposal = null;
                mView.setNoAudio();
            }
        });
    }

    @Override
    public ShareBody generateShareBody(String shareContent) {
        ArgProposalDetail mArg = mView.getArgument();
        ShareBody shareBody = new ShareBody();
        shareBody.title = mArg.proposalName;
        shareBody.content = shareContent;
        shareBody.shareUrl = mArg.shareUrl;
        shareBody.shareUrlWeXin = mArg.shareUrlWeXin;
        shareBody.shareImagePath = ConfigData.PORTRAITPATH + File.separator + "proposal.png";
        return shareBody;
    }

    @Override
    public void deleteTap(String tapId, String proposalId) {
        if (TextUtils.isEmpty(tapId)) {
            return;
        }
        ProposalApi.getInstance(mContext).deleteProposalTap(tapId, new OnResponseListener<ResponseTapDelete>() {
            @Override
            public void onSuccess(ResponseTapDelete body, ResponsePage page) {
                if (body != null) {
                    sendPropsalTap(null, proposalId, 1);
                }
            }

            @Override
            public void onFailure(ResponseError error) {
                if (error != null) {
                    mView.showToast("删除语音失败，" + error.message);
                } else {
                    mView.showToast("删除语音失败");
                }
            }
        }, mView);
    }

    @Override
    public MultipartBody.Part generateMultipartBody(String name, String fileName, String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        File uploadFile = new File(filePath);
        if (!uploadFile.exists()) {
            return null;
        }
        RequestBody requestFileBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath));
        return MultipartBody.Part.createFormData(name, fileName, requestFileBody);
    }

    @Override
    public void uploadTap(AudioTap audioTap, String proposalId) {
        MultipartBody.Part param = generateMultipartBody("file", Constant.outputTapFileName, audioTap.path);
        if (param == null) {
            return;
        }
        ProposalApi.getInstance(mContext).updateProposalTap(param, new OnResponseListener<ResponseTapFile>() {
            @Override
            public void onSuccess(ResponseTapFile body, ResponsePage page) {
                if (body != null) {
                    ResponseTapFile entity = body;
                    if (entity != null) {
                        audioTap.id = entity.getId() + "";
                        audioTap.url = entity.getDownLoadUrl();
                        sendPropsalTap(audioTap, proposalId, 0);
                    } else {
                        mView.showToast("上传语音失败");
                    }
                } else {
                    mView.showToast("上传语音失败");
                }
            }

            @Override
            public void onFailure(ResponseError error) {
                mView.showToast("上传语音失败");
            }
        }, mView);
    }

    @Override
    public void sendPropsalTap(AudioTap tap, String proposalPickNum, int flag) {
        if (TextUtils.isEmpty(proposalPickNum)) {
            return;
        }
        ParamSaveProposalTaps param = new ParamSaveProposalTaps();
        param.pickNum = proposalPickNum;
        List<ParamProposalTap> tapList = new ArrayList<>();
        ParamProposalTap proposalTap = new ParamProposalTap();
        if (flag == 0) { // 上传语音
            if (tap == null) {
                mView.showToast("您要上传的语音不存在");
                return;
            }
            proposalTap.fileId = tap.id;
            proposalTap.type = 2; // 语音为2
            proposalTap.content = tap.url; // 语音的网络地址
            long duration = tap.duration;
            proposalTap.duration = duration;
            tapList.add(proposalTap);
            param.message = tapList;
        } else { // 删除语音,只需要传一个pickNum
            param.message = tapList;
        }

        ProposalApi.getInstance(mContext).saveProposalTaps(param, new OnResponseListener<ResponseSaveTaps>() {
            @Override
            public void onSuccess(ResponseSaveTaps body, ResponsePage page) {
                if (flag == 0) {
                    mView.showToast("上传语音成功");
                    mAudioTapBindingProposal = tap;
                    mAudioTapBindingProposal.fromServer = true; // 上传成功后，fromServer为true
                    mView.setAudio(proposalTap.duration);
                }
                if (flag == 1) {
                    mView.showToast("删除语音成功");
                    mAudioTapBindingProposal = null;
                    mView.setNoAudio();
                }
            }

            @Override
            public void onFailure(ResponseError error) {
                if (flag == 0) {
                    mView.showToast("上传语音失败");
                }
                if (flag == 1) {
                    mView.showToast("删除语音失败");
                }
            }
        }, mView);
    }

    @Override
    public void performSendProposal() {
        CardInfo cardInfo = AppContext.getCurrentUser().getCardInfo();
        if (cardInfo == null) {
            mView.showToast(mContext.getString(R.string.alert_fill_info));
        } else {
            share(mView.getArgument().applicantName, cardInfo.getNickName());
        }
    }

    private void share(String applicantName, String agentName) {
        // 分享内容
        String shareContent = ProposalUtils.getShareContent(applicantName, agentName);
        // 分享数据
        ShareBody shareEntity = generateShareBody(shareContent);
        // 分享
        mView.openShare(shareEntity);
    }

    @Override
    public void performVoice() {
        new ProposalTapDialog()
                .supportFragmentManager(mView.getFrgManager())
                .setData(mAudioTapBindingProposal)
                .setOnTapListener(new ProposalTapDialog.OnProposalTapListener() {
                    @Override
                    public void onTapDelete(AudioTap tap) {
                        deleteTap(tap.id, mView.getArgument().proposalId);
                    }

                    @Override
                    public void onTapUpload(AudioTap tap) {
                        uploadTap(tap, mView.getArgument().proposalId);
                    }
                })
                .show(mView.getFrgManager(), "performVoice");
    }

    @Override
    public void sendProposal() {
        ProposalApi.getInstance(mContext).sendProposal(mView.getArgument().proposalId, new OnResponseListener<ResponseSendProposal>() {
            @Override
            public void onSuccess(ResponseSendProposal body, ResponsePage page) {
//                mView.showToast("计划书发送成功");
                mView.initViewByDetailMode();
                sendEvent();
            }

            @Override
            public void onFailure(ResponseError error) {

            }

            private void sendEvent() {
                ProposalListTabCheckedEvent event = new ProposalListTabCheckedEvent();
                event.position = -1;
                EventBus.getDefault().post(event);
            }
        }, mView);
    }
}
